#include "message.h"

CmdType Message::getCmdType() const
{
    return cmdType;
}

QString Message::getTo() const
{
    return to;
}

QString Message::getFrom() const
{
    return from;
}

QString Message::getBody() const
{
    return body;
}

void Message::setFrom(const QString &newFrom)
{
    from = newFrom;
}

Message::Message() {}

Message::Message(CmdType cmdType, const QString &to, const QString &from, const QString &body) : cmdType(cmdType),
    to(to),
    from(from),
    body(body)
{}

QByteArray Message::toByteArray() const
{
    return toString().toUtf8();
}

QString Message::toString() const
{
    QJsonObject obj;
    int iCmdtype = cmdType;
    obj.insert(CMD_TYPE, QJsonValue(iCmdtype));
    obj.insert(TO, QJsonValue(to));
    obj.insert(BODY, QJsonValue(body));
    obj.insert(FROM, QJsonValue(from));
    auto now = QDateTime::currentDateTime();
    auto nowStr = now.toString("yyyy-MM-dd hh:mm");
    obj.insert(TS, nowStr);

    QJsonDocument doc(obj);
    auto msgStr = QString(doc.toJson(QJsonDocument::Compact));

    return msgStr;
}

Message* Message::fromByteArray(QByteArray &byteArray)
{
    auto doc = QJsonDocument::fromJson(byteArray);
    auto obj = doc.object();
    auto cmdType = static_cast<CmdType>(obj[CMD_TYPE].toInt());
    auto msg = new Message(cmdType, obj[TO].toString(), obj[FROM].toString(), obj[BODY].toString());
    return msg;
}


